package com.geen.tuoke.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.ToastUtils
import com.geen.tuoke.R
import com.geen.tuoke.base.BaseActivity
import com.geen.tuoke.bean.CustomerInfo
import com.geen.tuoke.databinding.ActivityAddCustomerBinding
import com.geen.tuoke.ui.viewmodel.CustomerViewModel
import com.geen.tuoke.utils.ext.initMenu
import kotlinx.android.synthetic.main.include_toolbar.*

/**
 * @Desc 添加客户
 */
class AddOrEditCustomerActivity : BaseActivity<CustomerViewModel, ActivityAddCustomerBinding>(),
    CustomerViewModel.Handler {

    private var isEdit = false

    private val customerInfo: CustomerInfo by lazy {
        ((intent.getSerializableExtra("customerInfo") as CustomerInfo?)).run {
            isEdit = this != null
            //如果为空的话  给个空值
            this ?: CustomerInfo()
        }
    }


    override fun getLayoutId(): Int {
        return R.layout.activity_add_customer
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        with(mBinding) {
            lifecycleOwner = this@AddOrEditCustomerActivity

            data = customerInfo
        }
        toolbar.initMenu(if (isEdit) "完善信息" else "添加客户", onBack = {
            finish()
        })


    }


    override fun initData() {
        mViewModel.addCustomerResult.observe(this) {
            finish()
        }

    }

    //点击添加客户 按钮
    fun addCustomer(view: View) {
        customerInfo?.let {
            mBinding.run {
                if (!RegexUtils.isMobileExact(etPhone.text)) {
                    ToastUtils.showShort("手机号输入有误")
                    return
                }
                if (!TextUtils.isEmpty(etEmail.text) && !RegexUtils.isEmail(etEmail.text)) {
                    ToastUtils.showShort("邮箱输入有误")
                    return
                }
            }

            it.gender = if (mBinding.rbMan.isChecked) 1 else 0

            mViewModel.addCustomer(it)
        }
    }


    companion object {
        fun start(context: Context, customerInfo: CustomerInfo?) {
            context.startActivity(Intent(context, AddOrEditCustomerActivity::class.java).apply {
                putExtra("customerInfo", customerInfo)
            })
        }
    }
}